  <template>
    <div>
      <Window :show="windowConfig.show" :buttons="windowConfig.buttons" @close="closeWindow">
        <el-form :rules="rules" :model="blogFormData" ref="blogFormRef">
          <el-form-item prop="title">
            <div class="input_title">
              <el-input placeholder="请输入博客标题" v-model="blogFormData.title"></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="content">
            <div :style="{ 'width': '100%' }">
              <EditorHtml v-if="blogFormData.editorType === 0" :height="editorHtmlHeight"
                v-model="blogFormData.content">
              </EditorHtml>
              <EditorMarkdown v-else @htmlContent="setHtmlContent" :height="editorMarkdownHeight"
                v-model="blogFormData.markdownContent">
              </EditorMarkdown>
            </div>
          </el-form-item>
        </el-form>

      </Window>
    </div>
  </template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, onUnmounted, proxyRefs, reactive, ref } from 'vue'
const { proxy } = getCurrentInstance();
const rules = {
  title: [{
    required: true, message: '请输入标题'
  }],
  categoryId: [{
    required: true, message: '请选择博客分类'
  }],
  content: [{
    required: true, message: '请选择输入正文'
  }],
  type: [{
    required: true, message: '请选择博客类型'
  }],
  allowComment: [{
    required: true, message: '请选择是否允许评论'
  }],
  reprintUrl: [{
    required: true, message: '请输入原文地址'
  }],
}

const editorMarkdownHeight = window.innerHeight - 60 - 20 - 30 - 50 - 10 - 50
const editorHtmlHeight = window.innerHeight - 60 - 20 - 30 - 50 - 100

const api = {
  'saveBlog': 'blog/saveBlog4Special',
  'getUserInfo': 'getUserInfo',
  'getBlogDetail': 'blog/getBlogById',
  'autoSave': 'blog/autoSaveBlog4Special'
}

const init = (type, data) => {
  startTimer();
  windowConfig.show = true;
  nextTick(() => {
    blogFormRef.value.resetFields();
    blogFormData.value = { categoryId: data.categoryId, pBlogId: data.blogId };
    if (type === 'add') {
      getUserInfo();
    } else {
      getBlogDetail(data.blogId)
    }
  })
}

defineExpose({
  init
})

const getUserInfo = async () => {
  let res = await proxy.Request({
    url: api.getUserInfo,
  })
  if (!res) {
    return;
  }
  blogFormData.value.editorType = res.data.editorType
}

const getBlogDetail = async (blogId) => {
  let res = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId
    }
  })
  if (!res) {
    return;
  }
  blogFormData.value = res.data
  if (res.data.tag) {
    blogFormData.value.tag = res.data.tag.split('|')
  } else {
    blogFormData.value.tag = [];
  }
}

let timer = ref(null);
const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 10000)
}

const clearTimer = () => {
  if (timer.value !== null) {
    clearInterval(timer.value)
    timer.value == null
  }
}

// 自动保存
const autoSave = async () => {
  if (blogFormData.value.title == undefined || blogFormData.value.content == undefined || dialogConfig.show || timer.value == null) {
    return;
  }
  const params = {}
  Object.assign(params, blogFormData.value)
  let res = await proxy.Request({
    url: api.autoSave,
    params,
  })
  if (res) {
    return;
  }
  blogFormData.value.blogId = res.data
}

const windowConfig = reactive({
  show: false,
  buttons: [{
    type: 'danger',
    text: '确定',
    click: (e) => {
      submitBlog();
    }
  }]
})


const emit = defineEmits();
const closeWindow = () => {
  windowConfig.show = false;
  emit('callback');
  if (timer.value !== null) {
    clearTimer();
  }
}


// 第一步提交
const blogFormRef = ref(null)
const blogFormData = ref({ tag: [] });
// markdown编辑器，设置html内容
const setHtmlContent = (htmlContent) => {
  blogFormData.value.content = htmlContent
}


const submitBlog = () => {
  blogFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = Object.assign({}, blogFormData.value)
    let res = await proxy.Request({
      url: api.saveBlog,
      params
    })
    if (!res) {
      return;
    }
    proxy.Message.success('保存博客成功')
    closeWindow();
  })
}

onUnmounted(() => {
  clearTimer();
})

</script>

<style lang='scss'>
.input_title {
  width: 100%;
  border-bottom: 1px solid #ddd;

  .el-input {
    .el-input__wrapper {
      box-shadow: none;

      input {
        font-size: 18px;
      }
    }
  }
}
</style>